<template>
  <!-- 结算中心/公司快递涨价规则 -->
  <page-container class="companyExpressPriceRules">
    <!-- 筛选项 -->
    <Operation>
      <operation-item name="大区" :isRequ="true">
        <a-select
          show-search
          placeholder="请选择大区"
          :filter-option="filterOption"
          style="width: 195px"
          @change="regionChange"
          v-model="regionId"
        >
          <a-select-option :key="index" v-for="(item, index) in regionList" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="城市" :isRequ="true">
        <a-select
          placeholder="请选择城市"
          show-search
          :filter-option="filterOption"
          style="width: 195px"
          @change="cityChange"
          v-model="cityId"
        >
          <a-select-option :key="index" v-for="(item, index) in cityList" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="仓库" :isRequ="true">
        <a-select
          show-search
          placeholder="请选择仓库"
          :filter-option="filterOption"
          style="width: 195px"
          @change="warehouseChange"
          v-model="organizeId"
        >
          <a-select-option :key="index" v-for="(item, index) in warehouseList" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="项目名称">
        <a-input style="width: 195px" v-model="projectName" placeholder="请输入项目名称" allowClear></a-input>
      </operation-item>
      <operation-item name="客户">
        <a-select
          style="width: 195px"
          show-search
          placeholder="请选择客户"
          :filter-option="filterOption"
          @change="customerChange"
          v-model="customerCode"
          allowClear
        >
          <a-select-option :key="index" v-for="(item, index) in customerList" :value="item.customerCode">
            {{ item.customerName }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="货主">
        <a-select
          style="width: 195px"
          show-search
          :filter-option="filterOption"
          @change="handleChange"
          v-model="ownerCode"
          allowClear
          placeholder="请选择货主"
        >
          <a-select-option :key="index" v-for="(item, index) in ownerList" :value="item.ownerCode">
            {{ item.ownerName }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="快递公司">
        <a-select
          style="width: 195px"
          show-search
          placeholder="请选择客户"
          :filter-option="filterOption"
          @change="companyChange"
          v-model="componyCode"
          allowClear
        >
          <a-select-option :key="index" v-for="(item, index) in logisticsList" :value="item.companyCode">
            {{ item.companyCode }}
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="状态">
        <a-select
          style="width: 195px"
          show-search
          placeholder="请选择状态"
          :filter-option="filterOption"
          v-model="status"
          allowClear
        >
          <a-select-option value="start">
            启用
          </a-select-option>
          <a-select-option value="stop">
            禁用
          </a-select-option>
        </a-select>
      </operation-item>
      <operation-item name="创建人">
        <a-input placeholder="请输入创建人" v-model="createBy" style="width:195px;" allowClear />
      </operation-item>
      <operation-item name="创建时间">
        <a-range-picker
          v-model="createTime"
          format="YYYY-MM-DD HH:mm:ss"
          :show-time="{
            format: 'HH:mm:ss',
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
          }"
          :placeholder="['Start Time', 'End Time']"
          @change="createChange"
          @ok="createOk"
          style="width:195px;"
        />
      </operation-item>
      <operation-item name="修改人">
        <a-input placeholder="请输入修改人" v-model="updateBy" style="width:195px;" allowClear />
      </operation-item>
      <operation-item name="修改时间">
        <a-range-picker
          v-model="updateTime"
          :show-time="{
            format: 'HH:mm:ss',
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
          }"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['Start Time', 'End Time']"
          @change="editChange"
          @ok="editOk"
          style="width:195px;"
        />
      </operation-item>
      <operation-item name="备注">
        <a-input style="width: 195px" v-model="remark" placeholder="请输入备注" allowClear></a-input>
      </operation-item>
      <!-- 按钮组 -->
      <SearchGroupBtn v-model="isOpen" @change="isOpenChange" @onSearch="onSearch" @onReset="onReset" />
    </Operation>
    <!-- 操作按钮 -->
    <AddBtn
      @showDrawer="showDrawer"
      @batchDelete="batchDelete"
      @exportExcel="exportExcelFun"
      :isDisabled="isDisabled"
    />
    <!-- 选中项 -->
    <SelectNum :selectNumber="selectNumber" @clearSelect="clearSelect" />
    <!-- 表格 -->
    <a-table
      :loading="tableLoading"
      :scroll="{ x: 1520 }"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      bordered
      rowKey="id"
    >
      <a slot="projectName" slot-scope="text, record" href="javascript:;" @click="selectDrawer(record)">
        {{ record.projectName }}
      </a>

      <span slot="config" slot-scope="text, record">
        <span
          v-for="(item, index) in record.ruleDetailInfo"
          :key="index"
          style="overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;"
        >
          <span v-if="item.markupWay === 'fixed'"
            >{{ `涨价名称：${item.markupName}，地区：` }}
            <span v-for="(item1, index1) in item.areaInfo" :key="index1">
              {{ item1.countryCode }}{{ item1.province }}{{ item1.city }}
            </span>
            {{
              `，加价方式：按固定值加价，价格（元）：${item.markupValue}，时间：${item.timeBegin}~${item.timeEnd}`
            }}</span
          >
          <span v-else>
            {{ `涨价名称：${item.markupName}，地区：` }}
            <span v-for="(item1, index1) in item.areaInfo" :key="index1">
              {{ item1.countryCode }}{{ item1.province }}{{ item1.city }}
            </span>
            {{ `，加价方式：按百分比加价，百分比：${item.markupValue}%，时间：${item.timeBegin}~${item.timeEnd}` }}
          </span>
        </span>
      </span>

      <a slot="action" slot-scope="text, record" href="javascript:;">
        <span v-if="isOneTake(record.ruleDetailInfo)" style="margin-right:8px;" @click="editDrawer(record)">修改</span>
        <span v-else style="margin-right:8px;color:#c2c2c2;" @click.prevent>修改</span>
        <span v-if="isOneTake(record.ruleDetailInfo)" @click="showModal(record)">删除</span>
        <span v-else style="color:#c2c2c2;">删除</span>
      </a>
    </a-table>
    <!-- 底部分页组件 -->
    <BottomPagination :total="total" @pageChange="pageChange" @sizeChange="sizeChange" />
    <!-- 确认删除对话框 -->
    <DelModal :visible="editVisible" @ok="handleOk" @cancel="handleNo" />
    <!-- 右滑抽屉 -->
    <!-- :isAdd="isAdd" -->
    <ExpressModal
      v-model="visible"
      :title="drawerTitle"
      @onSubmit="onSubmit"
      @onClose="onClose"
      :whCode="code"
      :customerList="customerList"
    />
    <!-- 提示是否覆盖冲突 -->
    <WarringModal
      title="提示"
      :msg="msg"
      :visible="WarringModalStatus"
      @ok="handleWarringOk"
      @cancel="handleWarringNo"
    />
  </page-container>
</template>

<script>
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    ellipsis: true,
    width: 90,
    customRender: (taxe, records, index) => `${index + 1}`
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    key: 'projectName',
    align: 'center',
    ellipsis: true,
    width: 110,
    scopedSlots: {
      customRender: 'projectName'
    }
  },
  {
    title: '客户',
    dataIndex: 'customerCode',
    key: 'customerCode',
    align: 'center',
    ellipsis: true,
    width: 110
  },
  {
    title: '货主',
    dataIndex: 'ownerCode',
    key: 'ownerCode',
    align: 'center',
    ellipsis: true,
    width: 100
  },
  {
    title: '快递公司',
    dataIndex: 'companyCode',
    key: 'companyCode',
    align: 'center',
    ellipsis: true,
    width: 100
  },
  {
    title: '规则配置',
    dataIndex: 'config',
    key: 'config',
    width: 400,
    scopedSlots: {
      customRender: 'config'
    },
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 120,
    ellipsis: true
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    key: 'createBy',
    align: 'center',
    width: 100,
    ellipsis: true
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center',
    width: 120,
    ellipsis: true
  },
  {
    title: '修改人',
    dataIndex: 'updateBy',
    key: 'updateBy',
    align: 'center',
    width: 100,
    ellipsis: true
  },
  {
    title: '项目备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
    width: 120,
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right',
    scopedSlots: {
      customRender: 'action'
    },
    align: 'center'
  }
]

import { getMarkupList, markupCreate, markupUpdate, markupDelete, markupExport } from '@/api/api'
import { delMixin } from '@/mixins/tableMixin'
export default {
  name: 'companyExpressPriceRules',
  mixins: [delMixin],
  data() {
    return {
      columns,
      // 抽屉相关
      visible: false,
      isAdd: true,
      msg: `测试`,
      WarringModalStatus: false,
      form: {
        customerCode: '',
        customerList: [],
        ownerCode: '',
        ownerList: [],
        ownerlist: [],
        region: '',
        city: '',
        name: '',
        regionId: '',
        cityId: '',
        organizeId: '',
        categoryId: '',
        financeName: '',
        tempType: '',
        amount: '',
        remark: '',
        createBy: '',
        createTime: [],
        editBy: '',
        editTime: [],
        collection: '',
        collectionTime: '',
        cascaderValue: []
      },
      rules: {
        collection: [{ required: true, message: '请选择记账归属', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        name: [{ required: true, message: '请选择仓库', trigger: 'change' }],
        customerCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
        ownerCode: [{ required: false, message: '请选择货主', trigger: 'change' }],
        cascaderValue: [{ required: true, message: '请选择收支项名称', trigger: 'change' }],
        tempType: [{ required: true, message: '请选择收支类型', trigger: 'change' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'change' }]
      },
      ruleDetailInfo: [
        {
          markupName: '加价名称',
          markupWay: '加价方式（fixed：按固定值，rate：按百分比）',
          markupValue: '加价值',
          timeBegin: '开始时间',
          timeEnd: '结束时间',
          sortNo: '排序标识',
          areaInfo: [
            {
              countryCode: '国家',
              province: '省份',
              city: '城市',
              area: '区域',
              town: '街道'
            }
          ]
        }
      ] //规则集合
    }
  },
  // TODO 计算属性:判断多选是否有不允许删除项
  methods: {
    handleWarringNo() {
      this.WarringModalStatus = false
    },

    // 覆盖创建
    async handleWarringOk(params) {
      const res = await markupCreate(params)
      if (res.success) {
        this.visible = false
        this.getTableData()
      } else {
        this.$message.warning(res.message)
      }
    },
    // 搜索
    onSearch() {
      this.onSearchCallback('搜索', () => {
        this.selectNumber = 0
        this.selectedRowKeys = []
        this.deletdBtnShow = false
        console.log('demo', '测试回调函数')
        this.getTableData()
      })
    },
    // 获取列表数据
    async getTableData() {
      this.tableLoading = true
      let params = {
        delFlag: 0,
        ruleType: 'CUST',
        projectName: this.projectName,
        componyCode: this.componyCode,
        ownerCode: this.ownerCode,
        customerCode: this.customerCode,
        // regionId: this.regionId,
        // cityId: this.cityId,
        organizeId: this.organizeId,
        categoryId: this.categoryId,
        createBy: this.createBy,
        updateBy: this.updateBy,
        createTime_begin: this.createTime_begin,
        createTime_end: this.createTime_end,
        updateTime_begin: this.updateTime_begin,
        updateTime_end: this.updateTime_end,
        status: this.status,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        remark: this.remark
      }
      const res = await getMarkupList(params)
      console.log(res)
      if (res.success) {
        this.tableLoading = false
        this.tableData = res.result.records
        this.total = res.result.total
      } else {
        this.$message.warning(res.message)
      }
    },
    // 导出
    exportExcelFun() {
      let params = {
        ids: this.ids,
        ruleType: 'CUST',
        organizeId: this.organizeId,
        delFlag: 0
      }
      this.onSearchCallback('导出', () => {
        markupExport(params).then(data => {
          console.log(data)
          this.downLoadTemp(data, '公司快递规则加价', 'xls')
        })
      })
    },
    // 确认删除
    async handleOk() {
      this.editVisible = false
      let params = {
        ids: this.ids
      }
      const res = await markupDelete(params)
      if (res.success) {
        this.getTableData()
        this.editVisible = false
      } else {
        this.editVisible = false
        this.$message.warning(res.message)
      }
    },
    //打开抽屉
    showDrawer() {
      this.onSearchCallback('新增', () => {
        this.visible = true
        this.drawerTitle = '创建公司快递涨价规则'
        this.$bus.$emit('isAdd', 'add')
      })
    },
    // 查看抽屉
    selectDrawer(record) {
      this.visible = true
      this.drawerTitle = '查看公司快递涨价规则'
      this.$bus.$emit('isAdd', 'select', record)
    },
    // 修改收支项
    editDrawer(record) {
      console.log(record, 'record')
      this.visible = true
      this.id = record.id
      this.drawerTitle = '修改公司快递涨价规则'
      this.$bus.$emit('isAdd', 'edit', record)
    },
    // 抽屉数据提交
    async onSubmit(form, list, flag) {
      console.log(form, list)

      // 开始处理数据  加价规则配置  ==》

      let arr = [] //存放货主编码
      let arr1 = [] //存放快递公司编码

      form.ownerCode.forEach(item => {
        arr.push(form.customerCodes.join(',') + '@' + item)
      })

      form.logisticsCompanyCode.forEach(item => {
        arr1.push(form.customerCodes.join(',') + '@' + item)
      })

      list.forEach((item, index) => {
        item.markupName = item.markupName //加价名称
        item.markupWay = item.markupWay //加价类型
        item.markupValue = item.markupWay === 'fixed' ? item.markupValue : item.proportion //固定值or百分比
        item.timeBegin = item.timeBegin //开始时间
        item.timeEnd = item.timeEnd //结束时间
        item.sortNo = index + 1 //排序标识
      })

      // 拼装请求参数 ==》

      let params = {
        id: this.id,
        organizeId: this.organizeId, //组织表仓库ID
        whCode: form.customerCode, //仓库编码
        projectName: form.projectName, //项目名称
        customerCode: form.customerCodes.join(','), //客户编码
        ownerCode: arr.join(','), //快递公司编码
        companyCode: arr1.join(','),
        ruleType: 'CUST',
        remark: form.remark,
        confirm: false,
        ruleDetailInfo: list
      }

      params.confirm = true

      // 数据处理完发送请求
      console.log(params)

      if (flag == 'edit') {
        const res = await markupUpdate(params)
        if (res.success) {
          this.visible = false
          this.$message.success(res.message)
          this.getTableData()
        } else {
          this.WarringModalStatus = res.message.indexOf('存在冲突') !== -1
          this.msg = res.message
          this.$message.warning(res.message)
        }
      } else {
        const res = await markupCreate(params)
        if (res.success) {
          this.visible = false
          this.$message.success(res.message)
          this.getTableData()
        } else {
          this.WarringModalStatus = res.message.indexOf('存在冲突') !== -1
          this.msg = res.message
          this.$message.warning(res.message)
        }
      }
    }
  },
  beforeDestroy() {
    this.$bus.$off('isAdd')
  }
}
</script>
